import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const billStore = createSlice({
  name: 'bill',
  initialState: {
    billList: []
  },
  reducers: {
    // 同步修改的方法
    setBillList: (state, action) => {
      state.billList = action.payload
    },
    addBill: (state, action) => {
      state.billList.push(action.payload)
    }
  }
})
// 异步修改的方法
const getBillList = () => {
  return (dispatch) => {
    axios.get('http://localhost:8888/ka').then((res) => {
      dispatch(setBillList(res.data))
    })
  }
}
// 新增数据
const addBillList = (data) => {
  return async (dispatch) => {
    const res = await axios.post('http://localhost:8888/ka', data)
    dispatch(addBill(res.data))
  }
}

const { setBillList, addBill } = billStore.actions
export { setBillList, addBill, getBillList, addBillList }
export default billStore.reducer
